import React from 'react'
import withLayout from '../components/Layout'
import axios from 'axios'
import { dateFormater } from '../utils/tool'
import Pagination from '../components/Pagination'
import Map from '../components/Map'


class House extends React.Component {
  handleGetMap = e => {
    const { lng, lat } = this.props
    const center = [lng, lat]
    const { right, top } = e.currentTarget.getBoundingClientRect()
    const x = right + 3
    const y = top + window.pageYOffset + 10
    Map.show({ center, x, y })
  }

  render() {
    const { prices, address, phone, title, yxdjTimeStart, kfs, } = this.props

    return (
      <div className="house-item">
        <h2 className="do-link">
          <span className="house-item-title">{title}</span>
          <img src="/static/marker.svg" alt="" onClick={this.handleGetMap} />
        </h2>
        <div><label>地址</label> {address}</div>
        <div><label>联系方式</label> {phone}</div>
        <div><label>价格</label> {prices[0]}-{prices[1]}</div>
        <div><label>开发商</label> {kfs}</div>
        <div><label>发布时间</label> {dateFormater(yxdjTimeStart)}</div>
      </div>
    )
  }
}

class Index extends React.Component {
  $map = React.createRef()
  map = null
  state = {
    list: [],
    pageNumber: 1,
    pageCount: 10,
    total: 0,
  }

  async componentDidMount() {
    await this.fetch()
  }

  fetch = async () => {
    const params = {
      pageNumber: this.state.pageNumber,
      pageCount: this.state.pageCount
    }
    const data = await axios.get('/houses', { params })
    const { list, pageNumber, pageCount, sum } = data
    this.setState({ list, pageNumber, pageCount, sum })
    return Promise.resolve(data)
  }

  handleTogglePage = pageNumber => {
    this.setState({ pageNumber }, this.fetch)
  }

  render() {
    const { list, pageNumber, sum, pageCount } = this.state
    return (
      <div className="">
        <div className="house-container">
          <div className="house-list">
            {list.map(info => <House key={info._id} {...info} />)}
            <Pagination total={sum} current={pageNumber} onChange={this.handleTogglePage} pageSize={pageCount} />
          </div>
        </div>
      </div>
    )
  }
}

export default withLayout(Index)